package com.sky.zzh.today;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHPost;
import com.next.net.SHTask;
import com.sky.widget.SHDialog;
import com.sky.widget.sweetdialog.SweetDialog;
import com.sky.zzh.R;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;

public class SleepPreQualityReport extends Activity implements ITaskListener {
	private CheckBox textViewSporting, textViewDinneroverhead, textViewDinnerLate;
	private SHGet tagTask;
	private SHPost tagUpdate;
	private String fromDate = "20150926", endDate = "20150927";
	private static final String TAG1 = "运动健身";
	private static final String TAG2 = "晚饭过量";
	private static final String TAG3 = "吃得晚了";
	private Button buttonBack, buttonUpdate;
	private ArrayList<String> SleepBofore = new ArrayList<String>();
	private MyCheckChangedListener mMyCheckChangedListener = new MyCheckChangedListener();
	private boolean isPre=false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sleepprequalityreport);
		textViewDinnerLate = (CheckBox) findViewById(R.id.textViewDinnerLate);
		textViewDinneroverhead = (CheckBox) findViewById(R.id.textViewDinneroverhead);
		textViewSporting = (CheckBox) findViewById(R.id.textViewSporting);
		buttonBack = (Button) findViewById(R.id.buttonBack);
		buttonUpdate = (Button) findViewById(R.id.btn_rightAccomplish);
		textViewSporting.setOnCheckedChangeListener(mMyCheckChangedListener);
		textViewDinnerLate.setOnCheckedChangeListener(mMyCheckChangedListener);
		textViewDinneroverhead.setOnCheckedChangeListener(mMyCheckChangedListener);

		buttonBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		buttonUpdate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isPre) {
					Toast.makeText(getApplicationContext(), "日子已过去，只能查看", Toast.LENGTH_SHORT).show();
					return;
				}
				JSONArray array = new JSONArray();
				String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
				try {
					for (String i : SleepBofore) {
						array.put(new JSONObject().put("Tag", i).put("TagType", "-1").put("UserTagDate", currentDateandTime));
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				System.out.println("SleepBofore" + SleepBofore);
//				SHDialog.ShowProgressDiaolg(SleepPreQualityReport.this);
				StringBuffer sb = new StringBuffer();
				sb.append(ConfigDefinition.URL);
				sb.append("user/UpdateUserTag");
				tagUpdate = new SHPost();
				tagUpdate.setListener(SleepPreQualityReport.this);
				tagUpdate.setUrl(sb.toString());
				tagUpdate.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
				tagUpdate.getTaskArgs().put("Tags", array);
				tagUpdate.start();
			}
		});

		fromDate = getIntent().getStringExtra("fromDate");
		endDate = getIntent().getStringExtra("endDate");
		String currentDate =
	            new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
	    if (Integer.valueOf(currentDate)>Integer.valueOf(endDate)) {
			isPre=true;
		}
		requestData(fromDate, endDate);
	}

	@Override
	public void onTaskFinished(SHTask task) throws Exception {
		SHDialog.dismissProgressDiaolg();
		JSONObject json = new JSONObject(task.getResult().toString());
		System.out.println("json:" + json);
		if (task == tagTask) {
			try {
				if ("200".equals(json.optString("ReturnCode"))) {
					JSONArray array = json.optJSONArray("Tags");
					int size = array.length();
					JSONObject obj = null;
					for (int i = 0; i < size; i++) {
						obj = array.getJSONObject(i);
						String TAG = obj.optString("Tag");
						int TagType = obj.optInt("TagType");
						if (TAG.equals(TAG1)) {
							// textViewSporting.setBackgroundColor(parseColor);
							textViewSporting.setChecked(true);
						}
						if (TAG.equals(TAG2)) {
							// textViewDinneroverhead.setBackgroundColor(parseColor);
							textViewDinneroverhead.setChecked(true);
						}
						if (TAG.equals(TAG3)) {
							// textViewDinnerLate.setBackgroundColor(parseColor);
							textViewDinnerLate.setChecked(true);
						}
					}
					if (isPre) {
						textViewSporting.setEnabled(false);
						textViewDinneroverhead.setEnabled(false);
						textViewDinnerLate.setEnabled(false);
			            }
				} else {
					SHDialog.dismissProgressDiaolg();
					new SweetDialog(this, SweetDialog.ERROR_TYPE).setTitleText("提示").setContentText(json.optString("ErrorMessage")).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (task == tagUpdate) {
			if ("200".equals(json.optString("ReturnCode"))) {
				Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	@Override
	public void onTaskFailed(SHTask task) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskUpdateProgress(SHTask task, int count, int total) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskTry(SHTask task) {
		// TODO Auto-generated method stub

	}

	private void requestData(String fromDate, String endDate) {
		SHDialog.dismissProgressDiaolg();
		if (tagTask != null) {
			tagTask.cancel(true);
		}
		SHDialog.ShowProgressDiaolg(this);
		tagTask = new SHGet();
		tagTask.setListener(this);
		StringBuffer sb = new StringBuffer();
		sb.append(ConfigDefinition.URL);
		sb.append("user/UserTags?UserId=");
		sb.append(UserInfoManager.getInstance().getUserId());
		sb.append("&");
		sb.append("FromDate=");
		sb.append(fromDate);
		sb.append("&");
		sb.append("EndDate=");
		sb.append(endDate);
		tagTask.setUrl(sb.toString());
		tagTask.start();
	}

	class MyCheckChangedListener implements OnCheckedChangeListener {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if (isChecked) {
				SleepBofore.add(buttonView.getText().toString());
			} else {
				SleepBofore.remove(buttonView.getText().toString());
			}
		}

	}

}
